package com.smedi.ismedi.progress.core.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.cache.starter.util.RedisUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.inmail.api.dto.request.MessageInfoRequest;
import com.smedi.ismedi.progress.core.application.command.*;
import com.smedi.ismedi.progress.core.application.query.ConstructionLogService;
import com.smedi.ismedi.progress.core.application.query.EngineeringrReportService;
import com.smedi.ismedi.progress.core.application.service.EngineeringReportApplicationService;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.*;
import com.smedi.ismedi.progress.core.domain.dto.PersonQuery;
import com.smedi.ismedi.progress.core.domain.repository.PersonRepository;
import com.smedi.ismedi.progress.core.domain.service.ExportExcelDomainService;
import com.smedi.ismedi.progress.core.domain.service.ProgrressReportDomainService;
import com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.progress.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.EngineeringWeekMonthReportEntity;
import com.smedi.ismedi.progress.core.port.adapter.service.MessageRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProcessRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProjectProgressService;
import com.smedi.ismedi.progress.core.port.adapter.service.TaskRemoteService;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.*;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MethodEnum.NOT_PASS;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MethodEnum.PASS;
import static com.smedi.ismedi.progress.core.infrastructure.constant.CustomError.DEAL_PERSON_NOT_FOUND;

/**
 * 工程报告应用服务实现类
 *
 * @author pengyan
 * @date 2022/11/23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EngineeringReportApplicationServiceImpl implements EngineeringReportApplicationService {
    private final EngineeringrReportService engineeringrReportService;
    private final ProjectProgressService projectProgressService;
    private final ExportExcelDomainService exportExcelDomainService;
    private final PersonRepository personRepository;
    private final AuthorityUtil authorityUtil;
    private final ConstructionLogService constructionLogService;
    private final TaskRemoteService taskRemoteService;
    private final ProgrressReportDomainService progrressReportDomainService;
    private final ProcessRemoteService processRemoteService;

    @Value("${message-notify.project-epc-manager.role}")
    private String messageNotifyProjectEpcManagerRole; //EPC项目经理 职务获取人员

    @Value("${deal-people.review-organization.role}")
    private String dealPersonReviewOrganizationRole; //主体院总承包部经理

    @Value("${message-notify.project-manager.role}")
    private String messageNotifyProjectManagerRole; //施工项目经理

    private final MessageRemoteService messageRemoteService;
    @Override
    public Page<EngineeringWeekMonthReport> getEngineeringReportListPC(EngineeringReportQuery engineeringReportQuery) {
        return engineeringrReportService.getEngineeringReportListPC(engineeringReportQuery,messageNotifyProjectEpcManagerRole,messageNotifyProjectManagerRole);
    }

    @Override
    public Page<EngineeringWeekMonthReport> getEngineeringReportListAPP(EngineeringReportQuery engineeringReportQuery) {
        return engineeringrReportService.getEngineeringReportListAPP(engineeringReportQuery,messageNotifyProjectEpcManagerRole);
    }

    // 本地锁，不支持多实例的部署
   private static final ConcurrentHashMap<String, Object> LOCAL_MAP = new ConcurrentHashMap<>();

    @Override
    /**
     * 主体院审批
     * EPC项目经理审批见:{@link EngineeringReportApplicationServiceImpl#reviewEngineeringReportEPCManager}
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean reviewEngineeringReportOrganization(ProgressReviewProjectCommand progressReviewProjectCommand) {
        String key = StrUtil.format("reviewEngineeringReportOrganization:{}", progressReviewProjectCommand.getId());
        Object o = LOCAL_MAP.get(key);
        synchronized ( this){
            if(o==null){
                LOCAL_MAP.put(key,new Object());
            }else {
                return false;
            }
        }
        EngineeringReportOneQuery engineerReport = engineeringrReportService.getEngineeringrReportOne(EngineeringReportOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        try {
            List<ProcessTask> processList = processRemoteService.getProcessList(ProcessListQuery.builder()
                    .businessType(ENGINEERING_WEEK_MONTH_REPORT)
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .processDefinitionKey(ENGINEERING_WEEKMONTH).build());
            if(CollUtil.isNotEmpty(processList)){
                // 再次校验是否重复审批
                Map<String, List<ProcessTask>> collect = processList.stream().collect(Collectors.groupingBy(ProcessTask::getName));
                if(CollUtil.isNotEmpty(collect)){
                    List<ProcessTask> mainGroup = collect.get("主体院待审批");
                    // 按开始时间排序,获取最新的节点审批状态
                    if(CollUtil.isNotEmpty(mainGroup)){
                        ProcessTask processTask = mainGroup.stream().max(Comparator.comparing(ProcessTask::getStartTime)).orElse(null);
                        if(processTask!=null && "completed".equals(processTask.getDeleteReason())   ){
                            return  true;
                        }
                    }
                }
            }
            Map<String, Object> variables = new HashMap<>();
            variables.put(METHOD, progressReviewProjectCommand.getMethod());
            ProjectBasicResponse projectData = progrressReportDomainService.getProject(engineerReport.getProjectId());
            String projectName = null;
            String projectId = null;
            String hrOrganizationFullName = null;
            if (projectData != null){
                if (projectData.getProjectName() != null ){
                    projectName = projectData.getProjectName();
                }
                if (projectData.getProjectId() != null ){
                    projectId = String.valueOf(projectData.getProjectId());
                }
                if (projectData.getHrOrganizationFullName() != null ){
                    hrOrganizationFullName = projectData.getHrOrganizationFullName();
                }
            }
            ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .businessType(ENGINEERING_WEEK_MONTH_REPORT)
                    .processDefinitionKey(ENGINEERING_WEEKMONTH)
                    .comment(progressReviewProjectCommand.getComment())
                    .variables(variables)
                    .build());
            taskRemoteService.editTask(TaskRecordEditCommand.builder()
                    .sourceFromId(engineerReport.getId())
                    .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                    .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_ORG_APPROVAL : ConstantField.MONTH_ENGINEERING_ORG_APPROVAL)
                    .taskStatus("已完成")
                    .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                    .finishTime(LocalDateTime.now())
                    .build());

            MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
            MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
            List<MessageInfoRequest> listDate = new ArrayList<>();
            messageInfoRequests.setMessageTitle(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE);
            messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
            messageInfoRequests.setProjectId(projectId);
            messageInfoRequests.setProjectName(projectName);
            messageInfoRequests.setPushTime(LocalDateTime.now());
            messageInfoRequests.setSourceFrom(ConstantField.ENGINEERING_FROM);
            if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {
                engineerReport.setTaskStatus(ConstantField.FINISHED);
                engineerReport.setTaskKey(ConstantField.ACTIVITY_FINISH);
                engineerReport.setStatus(6l);
//            engineerReport.setLatestUpdatedUserId(authorityUtil.getPersonId());
//            engineerReport.setLatestUpdatedDate(LocalDateTime.now());
                // 发送消息
                messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START +hrOrganizationFullName+"的"+projectName+ (ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)+ConstantField.MESSAGE_CONTENT_PASS_END);
                /**
                 * 1、工程部：按组织人员姓名发送，除去张峰、余为、季嵘、冯振伟
                 *
                 * 2、主体院：角色为“主体院总承包部经理”的人员
                 *
                 * 3、项目：项目职务为“施工项目经理”的人员
                 *
                 * 4、提交审批的人
                 *
                 */
                List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(engineerReport.getProjectId()).build());//施工项目经理
                List<Person> organPerson = personRepository.getPersonList(PersonQuery.builder().organizationId(2l).build());//安全管理部、工程管理部：按组织人员姓名发送，除去张峰、余为、季嵘、冯振伟
                organPerson.stream().filter(person -> (30 == person.getId() || 28 == person.getId() || 215 == person.getId() || 31 == person.getId())).collect(Collectors.toList());
                List<Person> personReviewOrganizationRole = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(engineerReport.getProject().getHrOrganizationId()).build());//主体院总承包部经理
                // 工程部：按组织人员姓名发送，除去张峰、余为、季嵘、冯振伟 未作
                messageNotifyProjectManager.add(engineerReport.getApplicant());// 提交审批的人
                messageNotifyProjectManager.addAll(personReviewOrganizationRole);// 主体院总承包部经理
                messageNotifyProjectManager.addAll(organPerson);
                messagesSendPostCommand.setUserIds(messageNotifyProjectManager.stream().distinct().map(Person -> Person.getId()).collect(Collectors.toList()));
            }
            final  String var_projectId=projectId;
            final  String var_projectName=projectName;
            final  String var_hrOrganizationFullName=hrOrganizationFullName;
            if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
                engineerReport.setStatus(2l);
                engineerReport.setReason(progressReviewProjectCommand.getComment());
//            engineerReport.setLatestUpdatedUserId(authorityUtil.getPersonId());
//            engineerReport.setLatestUpdatedDate(LocalDateTime.now());

                // 异步调用，防止异常调用影响本地事务数据更新
                CompletableFuture.runAsync(()->{
                    taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                            .sourceFromId(engineerReport.getId())
                            .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                            .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_BACK : ConstantField.MONTH_ENGINEERING_BACK)
                            .taskDescribe(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_APPROVAL_BACK : ConstantField.MONTH_ENGINEERING_APPROVAL_BACK)
                            .taskStatus("进行中")
                            .dealPersonId(engineerReport.getApplicant().getId())
                            .dealPersonName(engineerReport.getApplicant().getName())
                            .projectId(Long.parseLong(var_projectId))
                            .projectName(var_projectName)
                            .sponsorId(authorityUtil.getPersonId())
                            .sponsorName(authorityUtil.getLoginAccess().getLastName())
                            .startTime(LocalDateTime.now())
                            .build());
                });

                // 发送消息
                messageInfoRequests.setMessageContent(engineerReport.getApplicant().getName() + ConstantField.ENGINEERING_CONTENT_START +projectName+ (ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)+ ConstantField.APPROVAL_ORG + ConstantField.MESSAGE_CONTENT_NO_PASS_END);
                messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(engineerReport.getApplicant().getId())));
                // 发送短信
                CompletableFuture.runAsync(()->{
                    messageRemoteService.sendMessage(MessageSendCommand.builder()
                            .smsTemplateName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_NAME_WEEK_ENGINEERING_BACK : ConstantField.TASK_NAME_MONTH_ENGINEERING_BACK)
                            .mobiles(new ArrayList<>(Collections.singletonList(engineerReport.getApplicant().getMobile())))
                            .parameters(new ArrayList<>(Arrays.asList(var_hrOrganizationFullName, var_projectName,(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE),ConstantField.APPROVAL_ORG)))
                            .build());
                });

            }
            listDate.add(messageInfoRequests);
            messagesSendPostCommand.setMessageInfoRequests(listDate);
            // 修改为异步方式调用
            CompletableFuture.runAsync(()->{
                taskRemoteService.postSendMessage(messagesSendPostCommand);
            });
            engineeringrReportService.updateEngineeringrReport(engineerReport);
            return true;
        }catch (Exception e){
            throw  e;
        }finally {
            LOCAL_MAP.remove(key);
        }


    }

    @Override
    /**
     * epc项目经理审批
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean reviewEngineeringReportEPCManager(ProgressReviewProjectCommand progressReviewProjectCommand) {
        String key = StrUtil.format("reviewEngineeringReportEPCManager:{}", progressReviewProjectCommand.getId());
        Object o = LOCAL_MAP.get(key);
        synchronized ( this){
            if(o==null){
                LOCAL_MAP.put(key,new Object());
            }else {
                return false;
            }
        }
        try {
            EngineeringReportOneQuery engineerReport = engineeringrReportService.getEngineeringrReportOne(EngineeringReportOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
            List<ProcessTask> processList = new ArrayList<>();
            if(ConstantField.WEEK_TYPE ==  engineerReport.getType()){
                //周报
                processList = processRemoteService.getProcessList(ProcessListQuery.builder()
                        .businessType(ConstantField.CRANE)
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .processDefinitionKey(PROCESS_VERSION).build());


                if(CollUtil.isNotEmpty(processList)){
                    // 校验是否重复审批,如果重复提交立即返回
                    // 获取审批历史记录
                    Map<String, List<ProcessTask>> collect = processList.stream().collect(Collectors.groupingBy(ProcessTask::getName));
                    if(CollUtil.isNotEmpty(collect)){
                        List<ProcessTask> mainGroup = collect.get("施工项目经理待审批");
                        // 按开始时间排序,获取最新的节点审批状态
                        if(CollUtil.isNotEmpty(mainGroup)){
                            ProcessTask processTask = mainGroup.stream().max(Comparator.comparing(ProcessTask::getStartTime)).orElse(null);
                            if(processTask!=null && "completed".equals(processTask.getDeleteReason())   ){
                                return  true;
                            }
                        }
                    }
                }
            }else{
                //月报
                processList = processRemoteService.getProcessList(ProcessListQuery.builder()
                        .businessType(ENGINEERING_MONTH_REPORT)
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .processDefinitionKey(ENGINEERING_MONTH).build());
                if(CollUtil.isNotEmpty(processList)){
                    // 校验是否重复审批,如果重复提交立即返回
                    // 获取审批历史记录
                    Map<String, List<ProcessTask>> collect = processList.stream().collect(Collectors.groupingBy(ProcessTask::getName));
                    if(CollUtil.isNotEmpty(collect)){
                        List<ProcessTask> mainGroup = collect.get("EPC项目经理待审批");
                        // 按开始时间排序,获取最新的节点审批状态
                        if(CollUtil.isNotEmpty(mainGroup)){
                            ProcessTask processTask = mainGroup.stream().max(Comparator.comparing(ProcessTask::getStartTime)).orElse(null);
                            if(processTask!=null && "completed".equals(processTask.getDeleteReason())   ){
                                return  true;
                            }
                        }
                    }
                }
            }

            Map<String, Object> variables = new HashMap<>();
            variables.put(METHOD, progressReviewProjectCommand.getMethod());
            ProjectBasicResponse projectData = progrressReportDomainService.getProject(engineerReport.getProjectId());
            String projectName = null;
            String projectId = null;
            String hrOrganizationFullName = null;
            if (projectData != null){
                if (projectData.getProjectName() != null ){
                    projectName = projectData.getProjectName();
                }
                if (projectData.getProjectId() != null ){
                    projectId = String.valueOf(projectData.getProjectId());
                }
                if (projectData.getHrOrganizationFullName() != null ){
                    hrOrganizationFullName = projectData.getHrOrganizationFullName();
                }
            }
            /*List<Person> dealPeopleReviewOrganization = new ArrayList<>();
            if(WEEK_TYPE == engineerReport.getType()){
                dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(messageNotifyProjectManagerRole).organizationId(engineerReport.getProject().getHrOrganizationId()).build());
            }else{
                dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(engineerReport.getProject().getHrOrganizationId()).build());
            }*/
            //List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(engineerReport.getProject().getHrOrganizationId()).build());
//        if (dealPeopleReviewOrganization.isEmpty()){
//            throw LogicException.raise(new ErrorItem(30, "未找到对应项目的主体院总承包部经理角色，请配置主体院总承包部经理角色"));
//        }
            /*if (dealPeopleReviewOrganization.isEmpty()){
                throw LogicException.raise(DEAL_PERSON_NOT_FOUND, hrOrganizationFullName, this.dealPersonReviewOrganizationRole, ROLE);
            }*/
            if(WEEK_TYPE == engineerReport.getType()){
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(CRANE)
                        .processDefinitionKey(ConstantField.PROCESS_VERSION)
                        .comment(progressReviewProjectCommand.getComment())
                        .variables(variables)
                        .build());
                taskRemoteService.editTask(TaskRecordEditCommand.builder()
                        .sourceFromId(engineerReport.getId())
                        .taskType(ConstantField.TASK_WEEK_ENGINEERING_TYPE)
                        .taskName(ConstantField.WEEK_ENGINEERING_EPC_APPROVAL)
                        .taskStatus("已完成")
                        .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                        .finishTime(LocalDateTime.now())
                        .build());
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
            }else{
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(ENGINEERING_MONTH_REPORT)
                        .processDefinitionKey(ENGINEERING_MONTH)
                        .comment(progressReviewProjectCommand.getComment())
                        .variables(variables)
                        .build());
                taskRemoteService.editTask(TaskRecordEditCommand.builder()
                        .sourceFromId(engineerReport.getId())
                        .taskType(ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                        .taskName(ConstantField.MONTH_ENGINEERING_EPC_APPROVAL)
                        .taskStatus("已完成")
                        .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                        .finishTime(LocalDateTime.now())
                        .build());
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
            }
            MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
            MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
            List<MessageInfoRequest> listDate = new ArrayList<>();
            messageInfoRequests.setMessageTitle(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE);
            messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
            messageInfoRequests.setProjectId(projectId);
            messageInfoRequests.setProjectName(projectName);
            messageInfoRequests.setPushTime(LocalDateTime.now());
            messageInfoRequests.setSourceFrom(ConstantField.ENGINEERING_FROM);
            if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {
                //engineerReport.setStatus(4l);
//            engineerReport.setLatestUpdatedUserId(authorityUtil.getPersonId());
//            engineerReport.setLatestUpdatedDate(LocalDateTime.now());



                /*for (Person person : dealPeopleReviewOrganization) {
                    taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                            .sourceFromId(engineerReport.getId())
                            .dealPersonId(person.getId())
                            .dealPersonName(person.getName())
                            .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                            .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_ORG_APPROVAL : ConstantField.MONTH_ENGINEERING_ORG_APPROVAL)
                            .taskDescribe(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_DESCRIBE : ConstantField.MONTH_ENGINEERING_DESCRIBE)
                            .taskStatus("进行中")
                            .projectId(Long.parseLong(projectId))
                            .projectName(projectName)
                            .sponsorId(authorityUtil.getPersonId())
                            .sponsorName(authorityUtil.getLoginAccess().getLastName())
                            .startTime(LocalDateTime.now())
                            .build());
                    // 发送短信
                    messageRemoteService.sendMessage(MessageSendCommand.builder()
                            .smsTemplateName(ConstantField.WEEK_MONTH_ENGINEERING)
                            .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                            .parameters(new ArrayList<>(Arrays.asList(person.getName(), projectName)))
                            .build());
                }*/
                // 发送消息
                engineerReport.setTaskStatus(ConstantField.FINISHED);
                engineerReport.setTaskKey(ConstantField.ACTIVITY_FINISH);
                engineerReport.setStatus(6l);
                messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START +hrOrganizationFullName+"的"+projectName+ (ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)+ConstantField.MESSAGE_CONTENT_PASS_END);
                /**
                 * 1、工程部：按组织人员姓名发送，除去张峰、余为、季嵘、冯振伟
                 *
                 * 2、主体院：角色为“主体院总承包部经理”的人员
                 *
                 * 3、项目：项目职务为“施工项目经理”的人员
                 *
                 * 4、提交审批的人
                 *
                 */
                List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(engineerReport.getProjectId()).build());//施工项目经理
                List<Person> organPerson = personRepository.getPersonList(PersonQuery.builder().organizationId(2l).build());//安全管理部、工程管理部：按组织人员姓名发送，除去张峰、余为、季嵘、冯振伟
                organPerson.stream().filter(person -> (30 == person.getId() || 28 == person.getId() || 215 == person.getId() || 31 == person.getId())).collect(Collectors.toList());
                List<Person> personReviewOrganizationRole = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(engineerReport.getProject().getHrOrganizationId()).build());//主体院总承包部经理
                // 工程部：按组织人员姓名发送，除去张峰、余为、季嵘、冯振伟 未作
                messageNotifyProjectManager.add(engineerReport.getApplicant());// 提交审批的人
                messageNotifyProjectManager.addAll(personReviewOrganizationRole);// 主体院总承包部经理
                messageNotifyProjectManager.addAll(organPerson);
                messagesSendPostCommand.setUserIds(messageNotifyProjectManager.stream().distinct().map(Person -> Person.getId()).collect(Collectors.toList()));
            }
            if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
                engineerReport.setStatus(2l);
                engineerReport.setReason(progressReviewProjectCommand.getComment());
//            engineerReport.setLatestUpdatedUserId(authorityUtil.getPersonId());
//            engineerReport.setLatestUpdatedDate(LocalDateTime.now());
                taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                        .sourceFromId(engineerReport.getId())
                        .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                        .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_BACK : ConstantField.MONTH_ENGINEERING_BACK)
                        .taskDescribe(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_APPROVAL_BACK : ConstantField.MONTH_ENGINEERING_APPROVAL_BACK)
                        .taskStatus("进行中")
                        .dealPersonId(engineerReport.getApplicant().getId())
                        .dealPersonName(engineerReport.getApplicant().getName())
                        .projectId(Long.parseLong(projectId))
                        .projectName(projectName)
                        .sponsorId(authorityUtil.getPersonId())
                        .sponsorName(authorityUtil.getLoginAccess().getLastName())
                        .startTime(LocalDateTime.now())
                        .build());
                // 发送消息
                messageInfoRequests.setMessageContent(engineerReport.getApplicant().getName() + ConstantField.ENGINEERING_CONTENT_START +projectName+ (ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)+ ConstantField.APPROVAL_PROJECT + ConstantField.MESSAGE_CONTENT_NO_PASS_END);
                messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(engineerReport.getApplicant().getId())));

                // 发送短信
                messageRemoteService.sendMessage(MessageSendCommand.builder()
                        .smsTemplateName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_NAME_WEEK_ENGINEERING_BACK : ConstantField.TASK_NAME_MONTH_ENGINEERING_BACK)
                        .mobiles(new ArrayList<>(Collections.singletonList(engineerReport.getApplicant().getMobile())))
                        .parameters(new ArrayList<>(Arrays.asList(engineerReport.getApplicant().getName(), projectName,(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE), APPROVAL_EPC)))
                        .build());
            }
            listDate.add(messageInfoRequests);
            messagesSendPostCommand.setMessageInfoRequests(listDate);

            taskRemoteService.postSendMessage(messagesSendPostCommand);
            engineeringrReportService.updateEngineeringrReport(engineerReport);
            return true;
        }catch (Exception e){
            throw  e;
        }finally {
            LOCAL_MAP.remove(key);
        }

    }

    @Override
    public ResponseEntity<byte[]> engineeringReportExport(EngineeringReportDetailQuery engineeringReportDetailQuery) throws IOException {
        ProjectBasicResponse project = projectProgressService.getProject(engineeringReportDetailQuery.getProjectId());
        EngineeringReportDetail engineeringReportDetail = engineeringrReportService.getEngineeringReportDetail(engineeringReportDetailQuery);
        if (engineeringReportDetail == null) {
            throw LogicException.raise(CustomError.NO_DATA_FOUND);
        }
        return exportExcelDomainService.engineeringReportExport(engineeringReportDetail,project.getHrOrganizationFullName(),engineeringReportDetailQuery.getWeekMonthType(),engineeringReportDetailQuery.getExportType());
    }

    @Override
    /**
     * 工程报告 提交人 撤销 请求
     */
    public Boolean engineeringReportCreateBack(ProgressReviewProjectCommand progressReviewProjectCommand) {
        EngineeringReportOneQuery engineerReport = engineeringrReportService.getEngineeringrReportOne(EngineeringReportOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(engineerReport.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        if(ConstantField.WEEK_TYPE == engineerReport.getType()){
            ProcessTask processTask = processRemoteService.cancelProcessTask(ProcessTaskCancelCommand.builder()
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .businessType(ConstantField.CRANE)
                    .processDefinitionKey(ConstantField.PROCESS_VERSION)
                    .build());
            engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
        }else{
            ProcessTask processTask = processRemoteService.cancelProcessTask(ProcessTaskCancelCommand.builder()
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .businessType(ENGINEERING_MONTH_REPORT)
                    .processDefinitionKey(ENGINEERING_MONTH)
                    .build());
            engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
        }

        engineerReport.setTaskStatus(ENGINEERING_CREATE_BACK);

        engineerReport.setStatus(3l);
            taskRemoteService.editTask(TaskRecordEditCommand.builder()
                    .sourceFromId(engineerReport.getId())
                    .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                    .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_EPC_APPROVAL : ConstantField.MONTH_ENGINEERING_EPC_APPROVAL)
                    .taskStatus("已完成")
                    .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                    .finishTime(LocalDateTime.now())
                    .build());
        List<Person> messageNotifyProjectEpcManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(engineerReport.getProjectId()).build());//epc项目经理
        for (Person person : messageNotifyProjectEpcManager){
            MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
            MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
            List<MessageInfoRequest> listDate = new ArrayList<>();
            messageInfoRequests.setMessageTitle(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE);
            messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
            messageInfoRequests.setProjectId(projectId);
            messageInfoRequests.setProjectName(projectName);
            messageInfoRequests.setPushTime(LocalDateTime.now());
            messageInfoRequests.setSourceFrom(ConstantField.ENGINEERING_FROM);
            // 发送消息
            messageInfoRequests.setMessageContent(person.getName() + ConstantField.MESSAGE_ENGINEERING_CONTEXT_START + projectName + ConstantField.MESSAGE_ENGINEERING_CONTEXT_END);
            messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(person.getId())));
            listDate.add(messageInfoRequests);
            messagesSendPostCommand.setMessageInfoRequests(listDate);
            taskRemoteService.postSendMessage(messagesSendPostCommand);
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.WEEK_MONTH_ENGINEERING_APPROVAL)
                    .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(person.getName(),projectName)))
                    .build());

        }
        engineeringrReportService.updateEngineeringrReport(engineerReport);
        return true;
    }

    @Override
    /**
     * 工程报告 EPC项目经理 撤销 请求
     */
    public Boolean engineeringReportEPCBack(ProgressReviewProjectCommand progressReviewProjectCommand) {
        EngineeringReportOneQuery engineerReport = engineeringrReportService.getEngineeringrReportOne(EngineeringReportOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(engineerReport.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        if(ConstantField.WEEK_TYPE == engineerReport.getType()){
            ProcessTask processTask = processRemoteService.cancelProcessTask(ProcessTaskCancelCommand.builder()
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .businessType(ConstantField.CRANE)
                    .processDefinitionKey(ConstantField.PROCESS_VERSION)
                    .build());
            engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
        }else{
            ProcessTask processTask = processRemoteService.cancelProcessTask(ProcessTaskCancelCommand.builder()
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .businessType(ENGINEERING_MONTH_REPORT)
                    .processDefinitionKey(ENGINEERING_MONTH)
                    .build());
            engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
        }


            /*ProcessTask processTask = processRemoteService.cancelProcessTask(ProcessTaskCancelCommand.builder()
                    .businessCode(String.valueOf(engineerReport.getId()))
                    .businessType(ENGINEERING_WEEK_MONTH_REPORT)
                    .processDefinitionKey(ENGINEERING_WEEKMONTH)
                    .build());*/
            engineerReport.setTaskStatus(ENGINEERING_EPC_BACK);
            //engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
            engineerReport.setStatus(2l);
            taskRemoteService.editTask(TaskRecordEditCommand.builder()
                    .sourceFromId(engineerReport.getId())
                    .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                    .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_APPROVAL_BACK : ConstantField.MONTH_ENGINEERING_APPROVAL_BACK)
                    .taskStatus("已完成")
                    .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                    .finishTime(LocalDateTime.now())
                    .build());
        // 获取主体院 人员
        /*List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(engineerReport.getProject().getHrOrganizationId()).build());
        for (Person person : dealPeopleReviewOrganization){
            MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
            MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
            List<MessageInfoRequest> listDate = new ArrayList<>();
            messageInfoRequests.setMessageTitle(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE);
            messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
            messageInfoRequests.setProjectId(projectId);
            messageInfoRequests.setProjectName(projectName);
            messageInfoRequests.setPushTime(LocalDateTime.now());
            messageInfoRequests.setSourceFrom(ConstantField.ENGINEERING_FROM);
            // 发送消息
            messageInfoRequests.setMessageContent(person.getName() + ConstantField.MESSAGE_ENGINEERING_CONTEXT_START + projectName + ConstantField.MESSAGE_ENGINEERING_CONTEXT_END);
            messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(person.getId())));
            listDate.add(messageInfoRequests);
            messagesSendPostCommand.setMessageInfoRequests(listDate);
            taskRemoteService.postSendMessage(messagesSendPostCommand);
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.WEEK_MONTH_ENGINEERING_APPROVAL)
                    .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(person.getName(),projectName)))
                    .build());

        }*/
        engineeringrReportService.updateEngineeringrReport(engineerReport);
        return true;
    }

    /**
     * 工程报告保存草稿与发布
     *
     * @param engineeringSaveAndDraft
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EngineeringReportOneQuery engineeringMonthWeekSaveDraftAndRelease(EngineeringWeekMonthReportSave engineeringSaveAndDraft) {
        // 获取
        // 保存工程报信息
        EngineeringWeekMonthReportSave engineeringWeekMonthReportSave = engineeringrReportService.engineeringWeekMonthSaveAndDraft(engineeringSaveAndDraft);
        EngineeringReportOneQuery engineerReport = engineeringrReportService.getEngineeringrReportOne(EngineeringReportOneQuery.builder().id(engineeringWeekMonthReportSave.getId()).build());

        if (DRAFT_METHOD.equals(engineeringSaveAndDraft.getMethod())){
            return engineerReport;
        }
        // 发送 epc 项目经理审批  ,月报
        List<Person> messageNotifyProjectEpcManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(engineeringWeekMonthReportSave.getProjectId()).build());
        //施工项目经理 审批，周报
        List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(engineeringWeekMonthReportSave.getProjectId()).build());
        if(ConstantField.WEEK_TYPE == engineerReport.getType()){
            //周报
            if (messageNotifyProjectManager.isEmpty()){
                throw LogicException.raise(DEAL_PERSON_NOT_FOUND, engineeringSaveAndDraft.getProjectName(), this.messageNotifyProjectManagerRole, PORJECT_JOB);
            }
        }else{
            //月报
            if (messageNotifyProjectEpcManager.isEmpty()){
                throw LogicException.raise(DEAL_PERSON_NOT_FOUND, engineeringSaveAndDraft.getProjectName(), this.messageNotifyProjectEpcManagerRole, PORJECT_JOB);
            }
        }

        if(2 != engineerReport.getStatus() && 3 != engineerReport.getStatus()){
            if(ConstantField.WEEK_TYPE == engineerReport.getType()){
                //周报
                processRemoteService.startProcessInstance(ProcessInstanceStartCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(ConstantField.CRANE)
                        .processDefinitionKey(ConstantField.PROCESS_VERSION)
                        .build());
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(CRANE)
                        .processDefinitionKey(PROCESS_VERSION)
                        .build());
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
            }else{
                //月报
                processRemoteService.startProcessInstance(ProcessInstanceStartCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(ENGINEERING_MONTH_REPORT)
                        .processDefinitionKey(ENGINEERING_MONTH)
                        .build());
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(ENGINEERING_MONTH_REPORT)
                        .processDefinitionKey(ENGINEERING_MONTH)
                        .build());
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
            }

        }

        if (2 == engineerReport.getStatus()){
            if(ConstantField.WEEK_TYPE == engineerReport.getType()){
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(CRANE)
                        .processDefinitionKey(PROCESS_VERSION)
                        .build());
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
                taskRemoteService.editTask(TaskRecordEditCommand.builder()
                        .sourceFromId(engineeringWeekMonthReportSave.getId())
                        .taskType(ConstantField.TASK_WEEK_ENGINEERING_TYPE)
                        .taskName(WEEK_ENGINEERING_BACK)
                        .taskStatus("已完成")
                        .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                        .finishTime(LocalDateTime.now())
                        .build());
            }else{
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(String.valueOf(engineerReport.getId()))
                        .businessType(ENGINEERING_MONTH_REPORT)
                        .processDefinitionKey(ENGINEERING_MONTH)
                        .build());
                engineerReport.setTaskStatus(processTask.getStatus());
                engineerReport.setTaskKey(processTask.getTaskDefinitionKey());
                taskRemoteService.editTask(TaskRecordEditCommand.builder()
                        .sourceFromId(engineerReport.getId())
                        .taskType(ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                        .taskName(ConstantField.MONTH_ENGINEERING_BACK)
                        .taskStatus("已完成")
                        .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                        .finishTime(LocalDateTime.now())
                        .build());
            }
        }
        engineerReport.setStatus(5l);
        // 更新主表
        engineeringrReportService.updateEngineeringrReport(engineerReport);
        //月报发送EPC项目经理待办，周报发送施工项目经理待办
        if(ConstantField.WEEK_TYPE == engineerReport.getType()){
            //周报
            List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(engineeringWeekMonthReportSave.getProjectId()).build());
            for (Person person : dealPeopleReviewOrganization) {
                // 发送待办
                taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                        .sourceFromId(engineeringWeekMonthReportSave.getId())
                        .taskType(ConstantField.TASK_WEEK_ENGINEERING_TYPE)
                        .taskName(WEEK_ENGINEERING_EPC_APPROVAL)
                        .taskDescribe(WEEK_ENGINEERING_DESCRIBE)
                        .dealPersonId(person.getId())
                        .dealPersonName(person.getName())
                        .taskStatus("进行中")
                        .projectId(engineerReport.getProject().getId())
                        .projectName(engineerReport.getProject().getName())
                        .sponsorId(authorityUtil.getPersonId())
                        .sponsorName(authorityUtil.getLoginAccess().getLastName())
                        .startTime(LocalDateTime.now())
                        .build());
                // 发送短信
                messageRemoteService.sendMessage(MessageSendCommand.builder()
                        .smsTemplateName(ConstantField.WEEK_MONTH_ENGINEERING)
                        .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                        .parameters(new ArrayList<>(Arrays.asList(person.getName(), engineerReport.getProject().getName())))
                        .build());
            }
        }else{
            //月报
            for (Person person : messageNotifyProjectEpcManager) {
                // 发送待办
                taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                        .sourceFromId(engineerReport.getId())
                        .taskType(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.TASK_WEEK_ENGINEERING_TYPE : ConstantField.TASK_MONTH_ENGINEERING_TYPE)
                        .taskName(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_EPC_APPROVAL : ConstantField.MONTH_ENGINEERING_EPC_APPROVAL)
                        .taskDescribe(ConstantField.WEEK_TYPE == engineerReport.getType() ? ConstantField.WEEK_ENGINEERING_DESCRIBE : ConstantField.MONTH_ENGINEERING_DESCRIBE)
                        .dealPersonId(person.getId())
                        .dealPersonName(person.getName())
                        .taskStatus("进行中")
                        .projectId(engineerReport.getProject().getId())
                        .projectName(engineerReport.getProject().getName())
                        .sponsorId(authorityUtil.getPersonId())
                        .sponsorName(authorityUtil.getLoginAccess().getLastName())
                        .startTime(LocalDateTime.now())
                        .build());
                // 发送短信
                messageRemoteService.sendMessage(MessageSendCommand.builder()
                        .smsTemplateName(ConstantField.WEEK_MONTH_ENGINEERING)
                        .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                        .parameters(new ArrayList<>(Arrays.asList(person.getName(), engineerReport.getProject().getName())))
                        .build());
            }
        }

        return engineerReport;
    }

    @Override
    public Boolean engineeringWeekReportNews() {
        WeekFields weekFields= WeekFields.ISO;
        LocalDateTime localDate1  = LocalDateTime.now().with(weekFields.dayOfWeek(), 1L);
        // 判断 当前时间 段是否有周报 未发布 无发送待办任务处理查看到编辑页面，每周日6点还未发布（包含休息日、节假日）
        LocalDate localDate = localDate1.toLocalDate();
        // 查询全部工程周报未完成的任务，下发通知
        List<EngineeringWeekMonthReportEntity> list  =  engineeringrReportService.selectAllNoty(localDate,ConstantField.WEEK_TYPE,ConstantField.WEEK_MONTH_RELEASE_STATUS);
        list.forEach(v->{
            // epc施工项目经理
            List<Person> messageNotifyProjectAssistantManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(v.getProjectId()).build());
            //Integer count = engineeringrReportService.findWeekReport(localDate,ConstantField.WEEK_TYPE,v.getProjectId(),v.getId(),ConstantField.WEEK_MONTH_RELEASE_STATUS);
                for (Person person : messageNotifyProjectAssistantManager){
                    // 发送待办
                    taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                            .sourceFromId(v.getId())
                            .taskType(TASK_WEEK_ENGINEERING_TYPE)
                            .taskName(ENGINEER_WEEK_NOT_RELEASE)
                            .taskDescribe(ENGINEER_WEEK_MESSAGE)
                            .taskStatus("进行中")
                            .dealPersonId(person.getId())
                            .dealPersonName(person.getName())
                            .projectId(v.getProjectId())
                            .projectName(v.getProjectName())
                            .sponsorName(SYSTEM_RELEASE)
                            .startTime(LocalDateTime.now())
                            .build());
                }
        });
        return true;
    }

    @Override
    public Boolean engineeringReportNews() {
        //本月第一天
        LocalDateTime now = LocalDateTime.now();
        LocalDate localDate = now.toLocalDate();
        LocalDate firstday = LocalDate.of (localDate.getYear (), localDate.getMonthValue (), 1);
        // 查询全部工程周报未完成的任务，下发通知
        List<EngineeringWeekMonthReportEntity> list  =  engineeringrReportService.selectAllNoty(firstday, MONTH_TYPE,ConstantField.WEEK_MONTH_RELEASE_STATUS);
        list.forEach(v->{
            // epc施工项目经理
            List<Person> messageNotifyProjectAssistantManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(v.getProjectId()).build());
            for (Person person : messageNotifyProjectAssistantManager){
                // 发送待办
                taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                        .sourceFromId(v.getId())
                        .taskType(TASK_MONTH_ENGINEERING_TYPE)
                        .taskName(ENGINEER_MONTH_NOT_RELEASE)
                        .taskDescribe(ENGINEER_MONTH_MESSAGE)
                        .taskStatus("进行中")
                        .dealPersonId(person.getId())
                        .dealPersonName(person.getName())
                        .projectId(v.getProjectId())
                        .projectName(v.getProjectName())
                        .sponsorName(SYSTEM_RELEASE)
                        .startTime(LocalDateTime.now())
                        .build());
            }

        });
        return true;
    }

    @Override
    public void handleTask(Long id) {
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .id(id)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
    }
}
